package com.chao.common.config.redis;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 存储字符串
     */
    public void setValue(String key,Object value){
        redisTemplate.opsForValue().set(key,value);
    }

    /**
     * 存储字符串
     */
    public void setValue(String key,Object value, long time){
        redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
    }

    /**
     * 存储map
     */
    public void setMap(String rkey,String key,Object value){
        redisTemplate.opsForHash().put(rkey,key,value);
    }

    /**
     * 存储list
     */
    public void setList(String rkey,Object value){
        redisTemplate.opsForList().leftPush(rkey,value);
    }


    /**
     * 获取字符串或java对象
     */
    public <T>T getValue(String key){
        return (T) redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取map
     */
    public JSONObject getMap(String rkey){
        return (JSONObject) JSONObject.toJSON(redisTemplate.opsForHash().entries(rkey));
    }

    /**
     * 获取map
     */
    public <T>T getMap(String rkey,String key){
        return (T) redisTemplate.opsForHash().get(rkey,key);
    }

    /**
     * 获取list
     */
    public <T> List<T> getList(String key){
        return (List<T>) redisTemplate.opsForList().range(key,0,-1);
    }

    /**
     * 删除List 指定长度前的值
     */
    public void deleteList(String key,Integer i){
        if(redisTemplate.hasKey(key)){
            redisTemplate.opsForList().trim(key,i,redisTemplate.opsForList().size(key));
        }
    }

    /**
     * 清除key
     */
    public void delete(String key){
        if(key.contains("*")){
            Set<String> keys = redisTemplate.keys(key);
            keys.forEach(k->redisTemplate.delete(k));
            return;
        }
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
    }

    /**
     * 设置key有效期 单位 秒
     */
    public void setTime(String key,Integer time){
        if(redisTemplate.hasKey(key)){
            redisTemplate.expire(key,time,TimeUnit.SECONDS);
        }
    }

    /**
     * 判断key是否存在
     */
    public Boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }

    /**
     * 模糊查询key列表
     */
    public Set<String> matchKey(String key){
        return redisTemplate.keys(key);
    }
}
